package com.gzz.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gzz.common.R;
import com.gzz.pojo.Strategy;
import com.gzz.mapper.StrategyMapper;
import com.gzz.service.ImgsRespService;
import com.gzz.service.RedisService;
import com.gzz.service.StrategyService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gzz.utils.OssUtils;
import com.gzz.utils.RedisCache;
import com.gzz.utils.RedisKeyUtils;
import com.gzz.vo.StrategyDetailVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 周佳成
 * @since 2023-11-20
 */
@Service
public class StrategyServiceImpl extends ServiceImpl<StrategyMapper, Strategy> implements StrategyService {

	@Autowired
	ImgsRespService imgsRespService;

	@Autowired
	RedisCache redisCache;

	@Override
	public List<Strategy> getListByUserId(Long id) {
		LambdaQueryWrapper<Strategy> lambdaQueryWrapper = new LambdaQueryWrapper<>();
		lambdaQueryWrapper.eq(Strategy::getUserId,id);

		return list(lambdaQueryWrapper);
	}

	@Override
	public R<Page> getListByTitle(String keyword,int pageNo,int pageSize) {
		LambdaQueryWrapper<Strategy> lambdaQueryWrapper = new LambdaQueryWrapper<>();
		lambdaQueryWrapper.like(Strategy::getStTitle,keyword).orderByDesc(Strategy::getStZan);
		Page<Strategy> page1 = new Page<>(pageNo,pageSize);
		page(page1,lambdaQueryWrapper);
		List<Strategy> list = page1.getRecords();
		List<Strategy> newlist = new ArrayList<>();
		Map<String,Integer> map = redisCache.getCacheMap(RedisKeyUtils.MAP_KEY_USER_LIKED_COUNT);
		Set<String> set = map.keySet();
		if(map.isEmpty()){
			return R.success(page1);
		}
		//从缓存里读到临时的点赞数
		for(Strategy strategy : list){
			Long id = strategy.getStId();
			if(set.contains(id.toString())){
				strategy.setStZan(strategy.getStZan()+map.get(id.toString()));
			}
			newlist.add(strategy);
		}
		page1.setRecords(newlist);
		return R.success(page1);
	}

	@Override
	public R<StrategyDetailVo> getStrategyDetail(Long stId) {
		Strategy strategy = getById(stId);
		StrategyDetailVo strategyDetailVo = new StrategyDetailVo();
		BeanUtils.copyProperties(strategy,strategyDetailVo);
		List<String> imgs = imgsRespService.getlistByIdAndTypeId(strategyDetailVo,stId, OssUtils.StrategyTypeId);
		strategyDetailVo.setDetailImgs(imgs);
		if(imgs == null){
			return R.error("数据异常");
		}
		return R.success(strategyDetailVo);
	}
}
